const URL: string = import.meta.env.VITE_WS_URL

interface IMessage {
  type: string;
  from: string | number;
  to: string | number // 为0广播
  data: any
}

class WebSocketServer {
  private ws!: WebSocket;
  private eMap: Map<String, Array<Function>>;
  private userId: number | string
  constructor(userId: number | string) {
    this.connect(userId)
    this.userId = userId
    this.eMap = new Map<string, Array<any>>()
  }

  connect(userId: number | string) {
    this.ws = new WebSocket(URL + userId)
  }

  bindEvent() {
    this.ws.addEventListener('open', this.handleOpen, false)
    this.ws.addEventListener('close', this.handleClose, false)
    this.ws.addEventListener('error', this.handleError, false)
    this.ws.addEventListener('message', this.handleMessage, false)
  }

  handleOpen(event: any) {
    console.log(event);
  }

  handleClose(event: any) {
    console.log(event);
  }

  handleError(event: any) {
    console.log(event);
  }

  handleMessage(event: MessageEvent) {
    const data:any = JSON.parse(event.data)

    let type: string = data.type

    this.eMap.get(type)?.forEach(f => f())
  }

  send(message: IMessage) {
    this.ws.send(JSON.stringify(message))
  }

  listen(emit: string, callback: Function) {
    let list = this.eMap.get(emit)
    if (list) {
      list.push(callback)
      return
    }
    this.eMap.set(emit, [callback])
  }
}

export default WebSocketServer